package com.mornd.gulimall.auth.web.v1;

import com.mornd.gulimall.apis.member.IMemberClient;
import com.mornd.gulimall.apis.member.to.MemberRegistTo;
import com.mornd.gulimall.common.core.constant.ServerUrls;
import com.mornd.gulimall.common.core.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author: mornd
 * @dateTime: 2023/8/18 - 5:36
 */

@Slf4j
@Controller
public class RegistController {
    @Resource
    private IMemberClient memberClient;

    /**
     * 注册
     * <p>
     * 重定向携带参数使用 RedirectAttributes
     */
    @PostMapping("/regist")
    public String regist(@Validated MemberRegistTo to,
                         BindingResult bindingResult,
                         RedirectAttributes redirectAttributes,
                         Model model) {
        String redirect = "redirect:" + ServerUrls.AUTH + "/reg.html";

        if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
//            Map<String, String> errorMap = fieldErrors.stream().collect(Collectors.
//                    toMap(
//                            FieldError::getField,
//                            FieldError::getDefaultMessage,
//                            (existingValue, newValue) -> existingValue));
//
////            model.addAttribute("errors", errorMap);
//            redirectAttributes.addFlashAttribute("errors", errorMap);

            String defaultMessage = fieldErrors.get(0).getDefaultMessage();
            redirectAttributes.addFlashAttribute("error", "注册失败，" + defaultMessage);
            return redirect;
        }

        R r = null;
        try {
            r = memberClient.regist(to);
        } catch (Exception e) {
            log.error(e.getMessage());
            redirectAttributes.addFlashAttribute("error", "注册失败，服务器异常");
            return redirect;
        }
        if (r.isFail()) {
            redirectAttributes.addFlashAttribute("error", "注册失败，" + r.getMsg());
            return redirect;
        }

        return "redirect:" + ServerUrls.AUTH + "/login.html";
    }
}
